const express = require('express');
const multer = require('multer');
const cors = require('cors');
const path = require('path');
const fs = require('fs');
const os = require('os');
const net = require('net');

// 检查端口是否可用
function checkPortAvailable(port) {
  return new Promise((resolve) => {
    const server = net.createServer();
    server.listen(port, () => {
      server.once('close', () => {
        resolve(true);
      });
      server.close();
    });
    server.on('error', () => {
      resolve(false);
    });
  });
}

// 寻找可用端口
async function findAvailablePort(startPort, maxTries = 10) {
  for (let i = 0; i < maxTries; i++) {
    const port = startPort + i;
    const available = await checkPortAvailable(port);
    if (available) {
      return port;
    }
  }
  throw new Error(`无法在 ${startPort} - ${startPort + maxTries - 1} 范围内找到可用端口`);
}

// 读取配置文件
let config;
try {
  config = JSON.parse(fs.readFileSync(path.join(__dirname, '../config.json'), 'utf8'));
} catch (error) {
  console.error('无法读取配置文件，使用默认配置');
  config = {
    uploadDir: './uploads',
    port: 3001,
    maxFiles: 50,
    autoCreateDir: true
  };
}

const app = express();

// 处理上传目录路径 - 支持跨平台
let uploadDir;
if (path.isAbsolute(config.uploadDir)) {
  uploadDir = config.uploadDir;
} else {
  uploadDir = path.resolve(__dirname, '..', config.uploadDir);
}

// 创建临时下载目录（用于电脑发送文件到手机）
const downloadDir = path.join(uploadDir, 'to_mobile');

// 确保目标目录存在
if (config.autoCreateDir) {
  [uploadDir, downloadDir].forEach(dir => {
    if (!fs.existsSync(dir)) {
      try {
        fs.mkdirSync(dir, { recursive: true });
        console.log(`已创建目录: ${dir}`);
      } catch (error) {
        console.error(`创建目录失败: ${dir}`, error);
        process.exit(1);
      }
    }
  });
}

// 检查目录是否可写
try {
  fs.accessSync(uploadDir, fs.constants.W_OK);
  fs.accessSync(downloadDir, fs.constants.W_OK);
} catch (error) {
  console.error(`目录不可写: ${uploadDir} 或 ${downloadDir}`);
  console.error('请检查目录权限或更改配置文件中的 uploadDir');
  process.exit(1);
}

console.log(`系统信息: ${os.type()} ${os.arch()}`);
console.log(`上传目录: ${uploadDir}`);
console.log(`下载目录: ${downloadDir}`);

// CORS配置
app.use(cors({
  origin: '*',
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization']
}));

app.use(express.json());

// 配置multer存储 - 手机上传到电脑
const uploadStorage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    const originalName = Buffer.from(file.originalname, 'latin1').toString('utf8');
    const ext = path.extname(originalName);
    const name = path.basename(originalName, ext);
    const timestamp = Date.now();
    
    const finalName = `${name}_${timestamp}${ext}`;
    cb(null, finalName);
  }
});

// 配置multer存储 - 电脑发送到手机
const downloadStorage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, downloadDir);
  },
  filename: function (req, file, cb) {
    const originalName = Buffer.from(file.originalname, 'latin1').toString('utf8');
    const ext = path.extname(originalName);
    const name = path.basename(originalName, ext);
    const timestamp = Date.now();
    
    const finalName = `${name}_${timestamp}${ext}`;
    cb(null, finalName);
  }
});

// 配置multer
const uploadMulter = multer({
  storage: uploadStorage,
  limits: {
    fileSize: config.maxFileSize === 'unlimited' ? Infinity : parseInt(config.maxFileSize),
    files: config.maxFiles || 50
  }
});

const downloadMulter = multer({
  storage: downloadStorage,
  limits: {
    fileSize: config.maxFileSize === 'unlimited' ? Infinity : parseInt(config.maxFileSize),
    files: config.maxFiles || 50
  }
});

// 获取配置信息接口
app.get('/api/config', (req, res) => {
  res.json({
    success: true,
    config: {
      uploadDir: uploadDir,
      downloadDir: downloadDir,
      maxFiles: config.maxFiles,
      allowedFileTypes: config.allowedFileTypes,
      platform: os.type(),
      arch: os.arch()
    }
  });
});

// 手机上传文件到电脑
app.post('/api/upload', uploadMulter.array('files'), (req, res) => {
  try {
    if (!req.files || req.files.length === 0) {
      return res.status(400).json({ success: false, message: '没有文件被上传' });
    }

    const uploadedFiles = req.files.map(file => ({
      originalName: Buffer.from(file.originalname, 'latin1').toString('utf8'),
      filename: file.filename,
      size: file.size,
      path: file.path
    }));

    console.log(`📱➡️💻 手机上传 ${uploadedFiles.length} 个文件到电脑`);
    
    res.json({
      success: true,
      message: `成功上传 ${uploadedFiles.length} 个文件到电脑`,
      files: uploadedFiles
    });
  } catch (error) {
    console.error('上传错误:', error);
    res.status(500).json({ success: false, message: '上传失败', error: error.message });
  }
});

// 电脑发送文件到手机
app.post('/api/send-to-mobile', downloadMulter.array('files'), (req, res) => {
  try {
    if (!req.files || req.files.length === 0) {
      return res.status(400).json({ success: false, message: '没有文件被发送' });
    }

    const sentFiles = req.files.map(file => ({
      id: Date.now() + Math.random(),
      originalName: Buffer.from(file.originalname, 'latin1').toString('utf8'),
      filename: file.filename,
      size: file.size,
      path: file.path,
      uploadTime: new Date()
    }));

    console.log(`💻➡️📱 电脑发送 ${sentFiles.length} 个文件到手机`);
    
    res.json({
      success: true,
      message: `成功发送 ${sentFiles.length} 个文件到手机`,
      files: sentFiles
    });
  } catch (error) {
    console.error('发送错误:', error);
    res.status(500).json({ success: false, message: '发送失败', error: error.message });
  }
});

// 获取可下载的文件列表（手机端查看）
app.get('/api/download-list', (req, res) => {
  try {
    if (!fs.existsSync(downloadDir)) {
      return res.json({ success: true, files: [] });
    }
    
    const files = fs.readdirSync(downloadDir).map(filename => {
      const filePath = path.join(downloadDir, filename);
      const stats = fs.statSync(filePath);
      return {
        id: filename,
        filename,
        originalName: filename.replace(/_\d+(\.[^.]+)?$/, '$1'), // 移除时间戳
        size: stats.size,
        uploadTime: stats.mtime,
        downloadUrl: `/api/download/${encodeURIComponent(filename)}`
      };
    }).sort((a, b) => new Date(b.uploadTime) - new Date(a.uploadTime)); // 按时间倒序
    
    res.json({ success: true, files });
  } catch (error) {
    console.error('获取下载列表错误:', error);
    res.status(500).json({ success: false, message: '获取下载列表失败' });
  }
});

// 下载文件接口（手机端下载）
app.get('/api/download/:filename', (req, res) => {
  try {
    const filename = decodeURIComponent(req.params.filename);
    const filePath = path.join(downloadDir, filename);
    
    // 安全检查：确保文件在下载目录内
    const resolvedPath = path.resolve(filePath);
    const resolvedDownloadDir = path.resolve(downloadDir);
    
    if (!resolvedPath.startsWith(resolvedDownloadDir)) {
      return res.status(403).json({ success: false, message: '访问被拒绝' });
    }
    
    if (!fs.existsSync(filePath)) {
      return res.status(404).json({ success: false, message: '文件不存在' });
    }
    
    const stats = fs.statSync(filePath);
    const originalName = filename.replace(/_\d+(\.[^.]+)?$/, '$1'); // 移除时间戳
    
    res.setHeader('Content-Disposition', `attachment; filename="${encodeURIComponent(originalName)}"`);
    res.setHeader('Content-Length', stats.size);
    res.setHeader('Content-Type', 'application/octet-stream');
    
    const fileStream = fs.createReadStream(filePath);
    fileStream.pipe(res);
    
    console.log(`📱⬇️ 手机下载文件: ${originalName}`);
  } catch (error) {
    console.error('下载错误:', error);
    res.status(500).json({ success: false, message: '下载失败' });
  }
});

// 删除待下载文件
app.delete('/api/download/:filename', (req, res) => {
  try {
    const filename = decodeURIComponent(req.params.filename);
    const filePath = path.join(downloadDir, filename);
    
    // 安全检查
    const resolvedPath = path.resolve(filePath);
    const resolvedDownloadDir = path.resolve(downloadDir);
    
    if (!resolvedPath.startsWith(resolvedDownloadDir)) {
      return res.status(403).json({ success: false, message: '访问被拒绝' });
    }
    
    if (fs.existsSync(filePath)) {
      fs.unlinkSync(filePath);
      console.log(`🗑️ 删除文件: ${filename}`);
      res.json({ success: true, message: '文件已删除' });
    } else {
      res.status(404).json({ success: false, message: '文件不存在' });
    }
  } catch (error) {
    console.error('删除错误:', error);
    res.status(500).json({ success: false, message: '删除失败' });
  }
});

// 获取已上传文件列表（电脑端查看）
app.get('/api/files', (req, res) => {
  try {
    if (!fs.existsSync(uploadDir)) {
      return res.json({ success: true, files: [] });
    }
    
    const files = fs.readdirSync(uploadDir)
      .filter(filename => filename !== 'to_mobile') // 排除下载目录
      .map(filename => {
        const filePath = path.join(uploadDir, filename);
        const stats = fs.statSync(filePath);
        return {
          filename,
          size: stats.size,
          uploadTime: stats.mtime
        };
      });
    
    res.json({ success: true, files });
  } catch (error) {
    console.error('获取文件列表错误:', error);
    res.status(500).json({ success: false, message: '获取文件列表失败' });
  }
});

// 健康检查
app.get('/api/health', (req, res) => {
  res.json({ 
    status: 'ok', 
    uploadDir,
    downloadDir,
    platform: os.type(),
    arch: os.arch(),
    nodeVersion: process.version
  });
});

// 启动服务器
async function startServer() {
  try {
    const PORT = await findAvailablePort(config.port || 3001);
    
    if (PORT !== config.port) {
      console.log(`⚠️  配置的端口 ${config.port} 被占用，使用端口 ${PORT}`);
      
      // 更新配置文件中的端口
      config.port = PORT;
      try {
        fs.writeFileSync(path.join(__dirname, '../config.json'), JSON.stringify(config, null, 2));
        console.log(`✅ 已更新配置文件中的端口为 ${PORT}`);
      } catch (error) {
        console.log(`⚠️  无法更新配置文件，但服务器将在端口 ${PORT} 运行`);
      }
    }
    
    app.listen(PORT, '0.0.0.0', () => {
      console.log(`🚀 服务器运行在 http://0.0.0.0:${PORT}`);
      console.log(`📁 文件将保存到: ${uploadDir}`);
      console.log(`📥 下载文件目录: ${downloadDir}`);
      console.log(`🖥️  平台: ${os.type()} ${os.arch()}`);
      console.log(`📱 手机访问地址: http://[你的IP]:${config.clientPort || 3000}`);
    });
  } catch (error) {
    console.error('❌ 启动服务器失败:', error.message);
    process.exit(1);
  }
}

startServer(); 